package org.oschina.api.index.service;

import org.oschina.Constants;
import org.oschina.api.BaseService;
import org.oschina.api.index.dao.IndexDAO;
import org.oschina.api.index.model.Index;
import org.oschina.handler.lock.annotation.Lock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class IndexService extends BaseService {

	@Autowired
	private IndexDAO indexDAO;
	
	/**
	 * 返回根据ID主键
	 * @param id
	 * @return
	 */
	@Lock(key=Constants.LOCK_INDEX_FIND)
	public int getMajorById(int id)
	{
		Index index=_findById(id);
		if(index==null)
			throw new RuntimeException("ID为 '"+id+"' 的索引不存在");
		
		_updateMajor(id,1);
		return index.getMajor()+1;
	}
	
	/**
	 * 更新主键
	 * @param index
	 * @return
	 */
	private void _updateMajor(int id,int count)
	{
		indexDAO.updateMajor(id,count);
	}
	
	/**
	 * 根据ID返回
	 * @param id
	 * @return
	 */
	private Index _findById(int id)
	{
		return indexDAO.findById(id);
	}
}